package com.googlecode.battleofendor.synchroniation;

import java.util.HashMap;

import com.googlecode.battleofendor.synchroniation.messages.PositionInfo;
import com.jme.math.Vector3f;
import com.jme.scene.Spatial;


public abstract class Player {
	
	private HashMap<String, PositionInfo> ownPool = new HashMap<String, PositionInfo>();
	
	private HashMap<String, PositionInfo> foreignPool = new HashMap<String, PositionInfo>();
	
	public Player() {
	}
	
	public Runnable publishOwnPool(final Connection connection) {
		return new Runnable() {
			public void run() {
				while(!Thread.interrupted()) {
					for(PositionInfo info: ownPool.values()) {
						connection.writeObject(info);
					}
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		};
	}
	
	public void setSceneGraph(SceneGraph graph) {
		this.sceneGraph = graph;
	}
	
	private SceneGraph sceneGraph;
	
	public Runnable updateMirrorPool(final Connection connection) {
		return new Runnable() {
			public void run() {
				while(!Thread.interrupted()) {
					System.out.println("Reading.");
					Object message = connection.readObject();
					System.out.println("Message revieved.");
					
					if(message == null) {
						System.out.println("Was NULL");
						return;
					}
					
					System.out.println(message);
					
					if(message instanceof PositionInfo) {
						System.out.println("Was position info");
						PositionInfo info = (PositionInfo) message;
						
						if(!foreignPool.containsKey(((PositionInfo) message).name)) {
							sceneGraph.add(info);
						}						
						
						foreignPool.put(info.name, info);
					}
				}
			}
		};
	}
	
	public PositionInfo createSharedPositionInfo(Spatial spatial, String type, Vector3f dir, float speed) {
		PositionInfo info = new PositionInfo();
		info.dirx = dir.x;
		info.diry = dir.y;
		info.dirz = dir.z;
		info.name = spatial.getName();
		info.speed = speed;
		info.time = currentTimeMillis();
		info.type = type;
		info.x = spatial.getLocalTranslation().x;
		info.y = spatial.getLocalTranslation().y;
		info.z = spatial.getLocalTranslation().z;
		ownPool.put(info.name, info);
		return info;
	}
	
	public PositionInfo getPositionInfo(String name) {
		PositionInfo own = ownPool.get(name);
		if(own != null) {
			return own;
		}
		
		PositionInfo foreign = foreignPool.get(name);
		if(foreign != null) {
			return foreign;
		}
		
		return null;
	}
	
	public abstract long currentTimeMillis();
}
